<template>
  <div class="app-container" id="MonthlySettlement">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择日期" prop="date">
        <el-date-picker v-model="dateTime" type="month" placeholder="请选择月份" @change="dateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="provide">
        <el-input v-model="queryParams.provide" placeholder="请输入供应商" :disabled="provideShow" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" style="display:flex">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:materialsCompany:Export']">导出</el-button>
        <el-button size="mini" type="primary" v-if="wzShow" icon="el-icon-download" @click="importExcelFun"
          :loading="loadingbtn" :disabled="this.rz === '已入账'"
          v-hasPermi="['system:materialsCompany:ExcelFun']">导入</el-button>
        <el-button size="mini" type="primary" v-if="wzShow" icon="el-icon-upload2" @click="importUpData"
          :loading="loadingbtn" :disabled="this.rz === '已入账'"
          v-hasPermi="['system:materialsCompany:ExcelFun']">导入数据</el-button>
        <el-button type="primary" plain size="mini" v-if="wzShow" icon="el-icon-notebook-2" :disabled="rzDisabled"
          @click="RecordedClick" v-hasPermi="['system:materialsCompany:Recorded']">{{ rz }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table :data="tableData1" :key="tableKey">
      <el-table-column prop="index" label="序号">
      </el-table-column>
      <el-table-column>
        <template slot="header">
          {{ '月应付款报表' }}({{ this.queryParams.startTime }})
        </template>
        <el-table-column prop="provide" label="供应商">
        </el-table-column>
        <el-table-column prop="yqMoney" label="压库金额" width="110">
          <template slot-scope="scope">
            <span class="rightText"> {{ formatNumber(scope.row.yqMoney > 0 ? scope.row.yqMoney : '')
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mdMoney" label="买断金额" width="110">
          <template slot-scope="scope">
            <span class="rightText">{{ formatNumber(scope.row.mdMoney > 0 ? scope.row.mdMoney : '') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalMoney" label="合计金额" width="110">
          <template slot-scope="scope">
            <span class="rightText">{{ formatNumber(scope.row.totalMoney ? scope.row.totalMoney : '')
              }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column>
        <template slot="header">
          {{ '开票总金额：' }}
          <span class="kpNum">{{ formatNumber(this.allMoney) }}</span>
        </template>
        <el-table-column prop="province" label="营运公司">
          <el-table-column prop="yypj" label="配件" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.yypj > 0 ? scope.row.yypj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="yyrhy" label="润滑油" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.yyrhy > 0 ? scope.row.yyrhy : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="yyzlj" label="制冷剂" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.yyzlj > 0 ? scope.row.yyzlj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="yylt" label="轮胎" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.yylt > 0 ? scope.row.yylt : '') }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column prop="province" label="崇明巴士">
          <el-table-column prop="cmpj" label="配件" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.cmpj > 0 ? scope.row.cmpj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="cmrhy" label="润滑油" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.cmrhy > 0 ? scope.row.cmrhy : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="cmzlj" label="制冷剂" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.cmzlj > 0 ? scope.row.cmzlj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="cmlt" label="轮胎" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.cmlt > 0 ? scope.row.cmlt : '') }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="city" label="金山巴士">
          <el-table-column prop="jspj" label="配件" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.jspj > 0 ? scope.row.jspj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="jsrhy" label="润滑油" width="110">
            <template slot-scope="scope">
              <span class="rightText"> {{ formatNumber(scope.row.jsrhy > 0 ? scope.row.jsrhy : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="jszlj" label="制冷剂" width="110">
            <template slot-scope="scope">
              <span class="rightText">{{ formatNumber(scope.row.jszlj > 0 ? scope.row.jszlj : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="jslt" label="轮胎" width="110">
            <template slot-scope="scope">
              <span class="rightText"> {{ formatNumber(scope.row.jslt > 0 ? scope.row.jslt : '') }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="otherMoney" label="其他" width="110">
        <template slot-scope="scope">
          <span v-if="scope.row.otherMoney > 0" class="otherMoney" @click="puRecords(scope.row.provide)">{{
      formatNumber(scope.row.otherMoney) }}</span>
        </template>
      </el-table-column>
      <el-table-column label=" 封账">
        <template slot-scope="scope">
          <el-button type="text" size="small" :disabled="scope.row.otherMoney !== 0 || scope.row.isFz === true"
            @click="sealAccounts(scope.row)">
            封账
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" layout="total, sizes, prev, pager, next, jumper" :total="total"
      :page.sync="queryParams.pageNum" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :limit.sync="queryParams.pageSize" @pagination="getList1" />

    <el-dialog title="开票入账" :visible.sync="dialogVisible" width="30%" :show-close="false" :close-on-click-modal="false">
      <div>
        <el-checkbox v-model="checked2"> <span>共 <span style="font-size:20px;margin:5px 0;">{{ total }}</span>
            个供应商</span></el-checkbox>
      </div>
      <div>
        <el-checkbox v-model="checked" style="margin-top:15px"> <span>入账总金额:<span style="font-size:20px;"> {{
      formatNumber(this.allMoney) }}</span> </span></el-checkbox>
      </div>
      <div>
        <el-checkbox style="margin-top:15px" v-model="checked1"><span
            style="color:red;">注意：请确认入账金额,一但入账后不得修改,不得再次提交入账申请</span></el-checkbox>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rzCancel">取 消</el-button>
        <el-button type="primary" @click="rzAffirm" :loading="rzLoading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog style="margin-top:30vh" title="" :visible.sync="ShowVisible" width="40%" :show-close="false"
      :close-on-click-modal="false" :center="true">
      <span>数据正在导入中……</span>
    </el-dialog>

  </div>

</template>

<script>
import { listMoneyInfo, updateRecords } from "@/api/system/records";
import { insertByInvoice, wareList, excelUpload2, zxkMonthStorageInApi } from "@/api/system/Recorded"
export default {
  name: "MonthlySettlement",
  data() {
    return {
      tableData: [],
      tableData1: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: "",
        provide: ""
      },
      dateTime: [],
      showSearch: true,
      productGroup: false,
      provideShow: false,
      // 总条数
      total: 0,
      // 遮罩层
      loading: true,
      tableKey: '',
      deptName: "",
      allMoney: 0,
      dialogVisible: false,
      rzDisabled: false,
      rz: '入账',
      checked: false,
      checked1: false,
      checked2: false,
      rzLoading: false,
      loadingbtn: false,
      ShowVisible: false,
      wzShow: false

    }
  },
  created() {


    const User = localStorage.getItem('User');
    this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
    if (this.deptName !== '物资公司') {
      this.queryParams.provide = this.deptName;
      this.provideShow = true;
    } else {
      this.queryParams.provide = "";
      this.provideShow = false;
      this.wzShow = true;
    }
  },
  mounted() {
    this.FormData();
    this.wareList();
    this.getList();
  },
  methods: {
    // 导入
    importExcelFun() {
      this.Upload();
    },
    Upload() {
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      let Time = formattedStartDate;
      const file = document.createElement('input');
      file.accept = '.xls, .xlsx'; // 允许上传的文件类型
      file.type = 'file';
      file.click();
      let _this = this;
      file.onchange = function (target) {
        var selectedFile = file.files[0];
        let param = new FormData(); // 创建form对象
        param.append('file', selectedFile); // 通过append向form对象添加数据
        _this.loadingbtn = true;
        if (_this.tableData1.length > 0) {
          _this.$confirm('已经存在数据，是否需要覆盖?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            type: 'warning'
          }).then(() => {
            if (_this.loadingbtn) {
              _this.ShowVisible = true;
            }
            excelUpload2(param, Time)
              .then(data => {
                let res = data.data;
                if (res.code === 200) {
                  setTimeout(() => {
                    _this.$message.success('导入成功');
                  }, 500);
                  _this.getList();
                } else {
                  setTimeout(() => {
                    _this.$message.error(res.info);
                  }, 500);
                }
              })
              .finally(() => {
                _this.loadingbtn = false;
                if (!_this.loadingbtn) {
                  _this.ShowVisible = false;
                }
              });
          }).catch(() => {
            _this.$message({
              type: 'info',
              message: '取消数据覆盖'
            });
            _this.loadingbtn = false;
          });
        } else {
          if (_this.loadingbtn) {
            _this.ShowVisible = true;
          }
          excelUpload2(param, Time)
            .then(data => {
              let res = data.data;
              if (res.code === 200) {
                setTimeout(() => {
                  _this.$message.success('导入成功');
                }, 500);
                _this.getList();
              } else {
                setTimeout(() => {
                  _this.$message.error(res.info);
                }, 500);
              }
            })
            .finally(() => {
              _this.loadingbtn = false;
              if (!_this.loadingbtn) {
                _this.ShowVisible = false;
              }
            });
        }
      };
    },

    // 导入数据
    importUpData() {
      this.loadingbtn = true;
      zxkMonthStorageInApi({createTime: this.queryParams.startTime}).then(res => {
          if(res.code == 200) {
              this.$message.success("导入完成，请确认是否正确")
          } else {
            this.$message.error(res.msg)
          }
      }).finally(() => {
        this.loadingbtn =  false;
      })
    },


    // 入账
    RecordedClick() {
      if (this.allMoney == 0) {
        this.$message.warning('本月开票总金额为0,不得入账');
      } else {
        this.dialogVisible = true;
        this.checked = false;
        this.checked1 = false;
        this.checked2 = false;
      }
    },
    // 入账取消
    rzCancel() {
      this.dialogVisible = false;
      this.wareList();
    },
    // 入账确认
    rzAffirm() {
      if (this.checked === true && this.checked1 === true && this.checked2 === true) {
        // 将日期字符串转换为日期对象
        const dateObj = new Date(this.dateTime);

        // 获取年份和月份
        const year = dateObj.getFullYear();
        const month = dateObj.getMonth() + 1;

        // 格式化月份为两位数
        const formattedMonth = month < 10 ? `0${month}` : `${month}`;

        // 格式化日期
        const formattedStartDate = `${year}-${formattedMonth}`;
        let Time = formattedStartDate;
        this.rzLoading = true;
        insertByInvoice(Time).then(rst => {
          if (rst.code === 200) {
            this.$message.success(rst.msg);
            //  this.$store.commit('tagsView/SET_KP_STATUS', 1);
          } else {
            this.$message.error(rst.msg)
          }
          this.wareList();
          this.dialogVisible = false;
          this.rzLoading = false;

        })
      } else {
        this.$message.warning('请勾选注意事项');
      }

    },
    // 入账接口
    wareList() {
      let provideWare = '中心库';
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      let Time = formattedStartDate;
      wareList(Time, provideWare).then(rst => {
        if (rst.code === 200) {

          if (rst.rows.length === 0) {
            this.rz = "入账";
            this.rzDisabled = false
          } else if (rst.rows && rst.rows[0]) {
            if (rst.rows[0].status == "0") {
              this.rz = "入账";
              this.rzDisabled = false
            } else if (rst.rows[0].status == "1") {
              this.rz = "入账中";
              this.rzDisabled = true;
            } else {
              this.rz = "已入账";
              this.rzDisabled = true;
            }
          }


        }
      })
    },
    // 列表数据接口
    getList() {
      this.loading = true;
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      this.queryParams.startTime = formattedStartDate;

      listMoneyInfo(this.queryParams.startTime, this.queryParams.provide).then(response => {
        this.tableData = response.data;
        this.allMoney = this.tableData.length > 0 && this.tableData[0].allMoney !== null ? this.tableData[0].allMoney : 0;

        this.total = response.data.length;
        // 表格重新渲染
        this.tableKey = Date.now();
        this.loading = false;
      }).finally(() => {
        this.tableData1 = this.tableData.slice((this.queryParams.pageNum - 1) * this.queryParams.pageSize, this.queryParams.pageNum * this.queryParams.pageSize);
        this.tableData.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        })
      })
    },
    getList1() {
      this.tableData1 = this.tableData.slice((this.queryParams.pageNum - 1) * this.queryParams.pageSize, this.queryParams.pageNum * this.queryParams.pageSize);
      this.tableData.forEach((item, index) => {
        item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
      })
    },
    // 分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
    },
    // 日期改变刷新列表
    dateChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
      if (this.queryParams.provide != "") {
        this.rzDisabled = true;
      } else {
        this.wareList();
      }
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
      if (this.queryParams.provide != "") {
        this.rzDisabled = true;
      } else {
        this.wareList();
      }
    },
    // 封账功能
    sealAccounts(row) {
      this.$confirm('是否进行封账?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          provide: row.provide,
          status: "1"
        }
        updateRecords(params).then(rst => {
          if (rst.code === 200) {
            this.getList();
            this.$message({
              type: 'success',
              message: '封账成功!'
            });

          } else {
            this.$message({
              type: 'error',
              message: '封账失败!'
            });
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消封账'
        });
      });



    },
    // 其他金额明细
    puRecords(provide) {
      this.$router.push({
        name: 'records', query: {
          provide: provide, productGroup: this.productGroup, dateTime: this.queryParams.startTime
        }
      });
    },
    // 重置
    resetQuery() {
      this.queryParams.provide = "";
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.FormData();
      this.getList();
      this.wareList()
      this.allMoney = this.tableData.length > 0 && this.tableData[0].allMoney !== null ? this.tableData[0].allMoney : 0;
    },
    // 导出
    handleExport() {
      this.download('system/records/upload/export', {
        ...this.queryParams
      }, `月结报表${this.queryParams.startTime}.xlsx`)
    },
    // 日期格式转换
    FormData() {
      // 定义一个函数,用于格式化日期为"yyyy-MM"
      const formatDate = date => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      };

      // 获取当前日期
      const currentDate = new Date();
      // 获取当前月的上个月
      const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);

      // 设置dateTime的初始值为上个月,并格式化为"yyyy-MM"
      this.dateTime = formatDate(lastMonth);
    },
    // 数字转换
    formatNumber(value) {
      if (value) {
        let [integerPart, decimalPart] = value.toString().split('.');
        let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        if (decimalPart) {
          formattedNumber += '.' + decimalPart.slice(0, 3);
        }
        return formattedNumber;
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table thead.is-group th {
  background-color: #f8f8f9;
}

::v-deep .el-table__cell {
  text-align: center;
}

.otherMoney {
  color: blue;
  float: right;
}

.rightText {
  float: right;
}

.kpNum {
  font-weight: 600;
  color: red;
}
</style>
